﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using IMS.Api.Repository;
using IMS.Api.Entity;
using Microsoft.Extensions.Configuration;
using IMS.Api.Utils;
using IMS.Api.ParamModel;
using Microsoft.AspNetCore.Authorization;

namespace IMS.Api.Controllers
{
    // 全局验证token
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class ShoppingCartsController : ControllerBase
    {
        // 定义调用购物车表的接口
        private IRepository<ShoppingCarts> _shoppingCartsRepository;
        // 定义调用文章表的接口
        private IRepository<Commodities> _commoditiesRepository;
        // 定义调用用户表的接口
        private IRepository<Users> _usersRepository;
        // 定义token
        private TokenParameter _tokenParameter;
        // 定义配置访问接口
        private readonly IConfiguration _configuration;

        // 依赖注入
        public ShoppingCartsController(IConfiguration configuration, IRepository<ShoppingCarts> shoppingCartsRepository, IRepository<Commodities> commoditiesRepository, IRepository<Users> usersRepository)
        {
            _configuration = configuration;
            _shoppingCartsRepository = shoppingCartsRepository;
            _commoditiesRepository = commoditiesRepository;
            _usersRepository = usersRepository;
            // Token
            _tokenParameter =
                configuration
                    .GetSection("tokenParameter")
                    .Get<TokenParameter>();
        }

        // 获取购物车表数据
        [HttpGet]
        public dynamic GetShoppingCartsList([FromQuery] Pager pager)
        {
            // 页码（当前第几页）
            var pageIndex = pager.PageIndex;
            // 页大小（一页里面行的数量）
            var pageSize = pager.PageSize;
            // 购物车表
            var shoppingCarts = _shoppingCartsRepository.Table.ToList();

            // 判断购物车表是否为空
            if (shoppingCarts != null)
            {
                // 购物车表不为空
                // 判断是否进入回收站
                var recycle = pager.Recycle;
                if (recycle)
                {
                    // 进入回收站
                    // 查看状态为删除购物车表
                    var deletedCommodity = _shoppingCartsRepository.DeleteTable;
                    // 给状态为删除的购物车表分页
                    var deletedTable = deletedCommodity.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                    return JsonHelper.Serialize(new
                    {
                        Data = new { DeletedShoppingCarts = deletedTable, Pager = new { pageIndex, pageSize, PageTotal = deletedCommodity.Count() } },
                        Meta = new
                        {
                            Msg = "获取已删除购物车列表成功！",
                            Status = 200
                        }
                    });
                }
                else
                {
                    // 没有进入回收站
                    // 购物车表分页
                    var activedTable = shoppingCarts.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                    return JsonHelper.Serialize(new
                    {
                        Data = new { ShoppingCarts = activedTable, Pager = new { pageIndex, pageSize, PageTotal = shoppingCarts.Count() } },
                        Meta = new
                        {
                            Msg = "获取购物车列表成功！",
                            Status = 200
                        }
                    });
                }
            }
            else
            {
                // 购物车表为空
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "购物车列表获取异常！",
                        Status = 400
                    }
                });
            }

        }

        // 根据用户Id获取购物车详情
        [HttpGet("uid/{id}"), Route("uid")]
        public dynamic GetShoppingCartByPid(int id)
        {
            // 判断传入的Id是否在购物车表存在
            var shoppingCart = _shoppingCartsRepository.Table.ToList().Where(x => x.FromUserId == id);
            if (shoppingCart != null)
            {
                // 查询的Id的购物车表存在
                return JsonHelper.Serialize(new
                {
                    Data = shoppingCart,
                    Meta = new
                    {
                        Msg = "购物车数据获取成功！",
                        Status = 200
                    }
                });
            }
            else
            {
                // 查询的Id的购物车表不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "购物车数据获取异常！",
                        Status = 400
                    }
                });
            }
        }

        // 根据购物车Id获取购物车
        [HttpGet("id/{id}"), Route("id")]
        public dynamic GetShoppingCartById(int id)
        {
            // 判断传入的Id是否在购物车表存在
            var shoppingCart = _shoppingCartsRepository.GetById(id);
            if (shoppingCart != null)
            {
                // 查询的Id的购物车表存在
                return JsonHelper.Serialize(new
                {
                    Data = shoppingCart,
                    Meta = new
                    {
                        Msg = "购物车数据获取成功！",
                        Status = 200
                    }
                });
            }
            else
            {
                // 查询的Id的购物车表不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "购物车数据获取异常！",
                        Status = 400
                    }
                });
            }
        }

        // 添加新购物车
        [HttpPost]
        public dynamic AddShoppingCart(NewShoppingCart model)
        {
            // 用户Id
            var fromUserId = model.FromUserId;
            // 商品Id
            var commodityId = model.CommodityId;
            // 商品名称
            var commodityName = model.CommodityName;
            // 商品价格
            var commodityPrice = model.CommodityPrice;
            // 商品数量
            var commodityNum = model.CommodityNum;
            // 选中的参数
            var commodityParams = model.CommodityParams;
            // 商品图片id
            var commodityImagesId = model.CommodityImagesId;
            // 送货地址
            var commodityAddress = model.CommodityAddress;

            // 判断用户Id是否存在
            if (fromUserId <= 0 && commodityId <= 0)
            {
                // 用户Id和商品Id为空时
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "插入的购物车详情对应用户和商品不能为空，请确认后重试！",
                        Status = 400
                    }
                });
            }
            else
            {
                // 用户Id和对应商品存在
                var ShoppingCart = _shoppingCartsRepository.Table.Where(x => x.FromUserId == fromUserId && x.CommodityId == commodityId).ToList();
                // 判断要创建的购物车不存在
                if (ShoppingCart.Count() == 0)
                {
                    // 创建新购物车
                    var shoppingCart = new ShoppingCarts
                    {
                        FromUserId = fromUserId,
                        CommodityId = commodityId,
                        CommodityName = commodityName,
                        CommodityPrice = commodityPrice,
                        CommodityNum = commodityNum,
                        CommodityParams = commodityParams,
                        CommodityImagesId = commodityImagesId,
                        CommodityAddress = commodityAddress,
                    };
                    // 购物车插入
                    _shoppingCartsRepository.Insert(shoppingCart);
                    return JsonHelper.Serialize(new
                    {
                        Data = shoppingCart,
                        Meta = new
                        {
                            Msg = "加入购物车成功！",
                            Status = 200
                        }
                    });
                }
                else
                {
                    var cart = ShoppingCart.FirstOrDefault();
                    // 购物车详情
                    cart.CommodityNum = cart.CommodityNum + commodityNum;
                    // 更新购物车详情数据
                    _shoppingCartsRepository.Update(cart);

                    return JsonHelper.Serialize(new
                    {
                        Data = cart,
                        Meta = new
                        {
                            Msg = "加入购物车成功，数量添加！",
                            Status = 200
                        }
                    });
                }
            }
        }

        // 购物车信息修改
        [HttpPut("{id}")]
        public dynamic ModShoppingCart(int id, NewShoppingCart model)
        {
            var shoppingCart = _shoppingCartsRepository.GetById(id);
            // 判断所修改购物车Id是否存在
            if (shoppingCart != null)
            {
                // 商品数量
                shoppingCart.CommodityNum = model.CommodityNum;
                // 购物车更新
                _shoppingCartsRepository.Update(shoppingCart);
                return JsonHelper.Serialize(new
                {
                    Data = shoppingCart,
                    Meta = new
                    {
                        Msg = string.Format("你修改的购物车的id为: {0} ，已经修改成功，请注意查收！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 该购物车Id不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的购物车不存在，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }

        // 购物车状态可用信息修改
        [HttpPut("status/{id}"), Route("status")]
        public dynamic ModStatus(int id)
        {
            var shoppingCart = _shoppingCartsRepository.GetById(id);
            // 判断对应Id的购物车是否存在
            if (shoppingCart != null)
            {
                // 指定Id的购物车存在
                _shoppingCartsRepository.ActiveStatus(id);
                return JsonHelper.Serialize(new
                {
                    Data = shoppingCart,
                    Meta = new
                    {
                        Msg = string.Format("你修改的状态对应购物车的id为: {0} ，已经修改成功，请注意查收！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 指定Id的购物车不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的购物车不存在，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }

        // 购物车信息删除（伪删除）
        [HttpDelete("{id}")]
        public dynamic DeleteShoppingCart(int id)
        {
            var shoppingCart = _shoppingCartsRepository.GetById(id);
            // 判断对应Id的购物车是否存在
            if (shoppingCart != null)
            {
                // 对应Id的购物车存在
                // 伪删除操作
                _shoppingCartsRepository.PseudoDeletion(id);
                return JsonHelper.Serialize(new
                {
                    Data = shoppingCart,
                    Meta = new
                    {
                        Msg = string.Format("你删除的购物车Id为 {0} 的数据,伪删除成功！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 对应Id的购物车不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = string.Format("找不到的购物车Id为 {0} 的数据,执行伪删除操作,", id),
                        Status = 400
                    }
                });
            }
        }

        // 购物车信息删除（彻底删除）
        [HttpDelete("delete/{id}"), Route("delete")]
        public dynamic CompletelyDeleteShoppingCart(int id)
        {
            var shoppingCart = _shoppingCartsRepository.GetById(id);
            // 判断对应Id的购物车是否存在
            if (shoppingCart != null)
            {   // 指定Id的购物车存在
                // 彻底删除
                _shoppingCartsRepository.Delete(id);
                return JsonHelper.Serialize(new
                {
                    Data = shoppingCart,
                    Meta = new
                    {
                        Msg = string.Format("你删除的Id为 {0} 的购物车数据,彻底删除成功！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 指定Id的购物车不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = string.Format("找不到的Id为 {0} 的购物车数据,无法执行彻底删除操作,", id),
                        Status = 400
                    }
                });
            }
        }

        // 恢复被删除的购物车数据
        [HttpDelete("recovery/{id}"), Route("recovery")]
        public dynamic RecoveryShoppingCart(int id)
        {
            var shoppingCart = _shoppingCartsRepository.GetById(id);
            // 判断对应Id的购物车是否存在
            if (shoppingCart != null)
            {
                // 指定Id的购物车存在
                // 恢复数据
                _shoppingCartsRepository.Recovery(id);
                return JsonHelper.Serialize(new
                {
                    Data = shoppingCart,
                    Meta = new
                    {
                        Msg = string.Format("你恢复的购物车的id为: {0} ，已经恢复成功，请注意查收！", id),
                        Status = 200
                    }

                });
            }
            else
            {
                // 指定Id的购物车不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的购物车不存在，恢复错误，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }
    }
}
